package org.crl.blogsystem.controller;

import cn.dev33.satoken.stp.StpUtil;
import org.crl.blogsystem.entity.Comment;
import org.crl.blogsystem.entity.dto.CommentDTO;
import org.crl.blogsystem.message.ResponseMessage;
import org.crl.blogsystem.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true", methods = {RequestMethod.GET, RequestMethod.POST,  RequestMethod.DELETE, RequestMethod.PUT})
public class CommentController {
    public CommentDTO convert(Comment comment) {
        CommentDTO commentDTO = new CommentDTO();
        commentDTO.setId(comment.getId());
        commentDTO.setBlogId(comment.getBlog().getId());
        commentDTO.setContent(comment.getContent());
        commentDTO.setCreatedAt(comment.getCreatedAt());
        commentDTO.setUsername(comment.getUser().getUsername());
        commentDTO.setAvatar(comment.getUser().getAvatar());
        return commentDTO;
    }

    @Autowired
    ICommentService commentService;

    @PostMapping("/blog/{blogId}/comment")
    public ResponseMessage<CommentDTO> add(@PathVariable("blogId") Long blogId,@RequestBody CommentDTO commentDTO) {
        StpUtil.checkLogin();
        Comment comment = commentService.add(blogId, commentDTO);
        CommentDTO commentDTO1 = convert(comment);
        return ResponseMessage.success(commentDTO1);
    }

    @DeleteMapping("/delComment/{id}")
    public ResponseMessage<String> delete(@PathVariable("id") Long id) {
        StpUtil.checkLogin();
        commentService.delete(id);
        return ResponseMessage.success("删除成功");
    }

    @GetMapping("/blog/{blogId}/comments")
    public ResponseMessage<? extends Object> getByBlogId(@PathVariable("blogId") Long blogId) {
        StpUtil.checkLogin();
        List<Comment> comments = commentService.getListByBlogId(blogId);
        List<CommentDTO> commentDTOS = comments.stream().map(this::convert).toList();
        return commentDTOS != null ?  ResponseMessage.success(commentDTOS) : ResponseMessage.fail("没有评论");
    }
}
